package com.xwc.cloud.support.loadbalancer.zuul;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.xwc.cloud.support.loadbalancer.LoadbalancerSupportProperties;
import org.springframework.util.StringUtils;

/**
 * 类描述：网关的路由传递实现
 * 作者：徐卫超 (cc)
 * 时间 2022/4/7 9:53
 */
public class RouterIpHeaderWriteFilter extends ZuulFilter {

    private LoadbalancerSupportProperties loadbalancerSupportProperties;
    private ExtractTargetRouter extractTargetRouter;

    public RouterIpHeaderWriteFilter(LoadbalancerSupportProperties loadbalancerSupportProperties, ExtractTargetRouter extractTargetRouter) {
        this.loadbalancerSupportProperties = loadbalancerSupportProperties;
        this.extractTargetRouter = extractTargetRouter;
    }

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        String routerIp = extractTargetRouter.get();
        if (StringUtils.hasText(routerIp)) {
            RequestContext context = RequestContext.getCurrentContext();
            context.addZuulRequestHeader(loadbalancerSupportProperties.getIpRule().getRouterAttrName(), routerIp);
        }
        return null;
    }
}
